package com.yunhai.device.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunhai.common.dto.GlobalException;
import com.yunhai.common.dto.PaginationVo;
import com.yunhai.common.utils.ObjectUtil;
import com.yunhai.common.utils.ReflectionCopy;
import com.yunhai.device.mapper.DeviceInfoMapper;
import com.yunhai.device.mapper.DevicePreloadMapper;
import com.yunhai.device.mapper.TmsStoreMapper;
import com.yunhai.device.service.DevicePreloadService;
import com.yunhai.model.entity.dms.DmsDeviceInfoEntity;
import com.yunhai.model.entity.dms.DmsDevicePreloadEntity;
import com.yunhai.model.entity.tms.TmsStoreEntity;
import com.yunhai.model.vo.dms.DmsDevicePreloadQuery;
import com.yunhai.model.vo.dms.DmsDevicePreloadVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class DevicePreloadServiceImpl implements DevicePreloadService {

    @Resource
    private DevicePreloadMapper devicePreloadMapper;
    @Resource
    private DeviceInfoMapper deviceInfoMapper;

    @Resource
    private TmsStoreMapper storeMapper;

    /**
     * 获取 DevicePreload 分页列表
     */
    @Transactional
    public IPage getDevicePreloadPagination(PaginationVo paginationVo, DmsDevicePreloadQuery dmsDevicePreloadQuery ) throws Exception {

        IPage page = new Page( paginationVo.getPageIndex(), paginationVo.getPageSize() );
        LambdaQueryWrapper<DmsDevicePreloadEntity> lqs = new LambdaQueryWrapper();
        lqs.likeRight( dmsDevicePreloadQuery.getCode() != null,
                DmsDevicePreloadEntity::getCode,
                dmsDevicePreloadQuery.getCode());
        lqs.eq(dmsDevicePreloadQuery.getStoreId() != null,
                DmsDevicePreloadEntity::getStoreId  ,
                dmsDevicePreloadQuery.getStoreId());
        lqs.eq(dmsDevicePreloadQuery.getDeployStatus() != null,
                DmsDevicePreloadEntity::getDeployStatus,
                dmsDevicePreloadQuery.getDeployStatus());
        lqs.orderByDesc(DmsDevicePreloadEntity::getCreateTime);
        devicePreloadMapper.selectPage(page, lqs);

        List<DmsDevicePreloadEntity> record = page.getRecords();
        if( !ObjectUtil.isNotEmptyList(record)){
            return page;
        }

        Set<Long> storeIds =  record.stream().map(item->item.getStoreId()).collect(Collectors.toSet());
        List<TmsStoreEntity> tmsStoreEntities = storeMapper.selectBatchIds(storeIds);
        if( ObjectUtil.isNotEmptyList(tmsStoreEntities) ){
            for( DmsDevicePreloadEntity item : record ){
                tmsStoreEntities.stream().filter(row-> row.getId().equals(item.getStoreId()))
                        .findFirst().ifPresent(row->{
                            item.setStoreName(row.getName());
                            item.setStoreNumber(row.getNumber());
                        });
            }
        }

        return page;
    }


    /**
     * 获取 DevicePreload 所有数据
     *
     */
    @Transactional
    public List<DmsDevicePreloadEntity> getDevicePreloadAllList( DmsDevicePreloadQuery dmsDevicePreloadQuery ) throws Exception {

        LambdaQueryWrapper<DmsDevicePreloadEntity> lqs = new LambdaQueryWrapper();
        lqs.eq(dmsDevicePreloadQuery.getStoreId() != null,
                DmsDevicePreloadEntity::getStoreId  ,
                dmsDevicePreloadQuery.getStoreId());
        List<DmsDevicePreloadEntity> list = devicePreloadMapper.selectList(lqs);

        if( !ObjectUtil.isNotEmptyList(list) ){
            return new ArrayList<>();
        }

        Set<Long> storeIds =  list.stream().map(item->item.getStoreId()).collect(Collectors.toSet());
        List<TmsStoreEntity> tmsStoreEntities = storeMapper.selectBatchIds(storeIds);
        if( ObjectUtil.isNotEmptyList(tmsStoreEntities) ){
            for( DmsDevicePreloadEntity item : list ){
                tmsStoreEntities.stream().filter(row-> row.getId().equals(item.getStoreId()))
                        .findFirst().ifPresent(row->{
                            item.setStoreName(row.getName());
                            item.setStoreNumber(row.getNumber());
                        });
            }
        }

        return list;
    }


    /**
     * 获取 DevicePreload 详情
     */
    @Transactional
    public DmsDevicePreloadEntity getDevicePreloadDetail( Long id) throws Exception {

        DmsDevicePreloadEntity dmsDevicePreloadEntity = devicePreloadMapper.selectById(id);
        return dmsDevicePreloadEntity;
    }


    @Override
    public List<DmsDevicePreloadEntity> getDevicePreloadDetailByStoreIds(List<Long> storeIds) throws Exception {

        if( !ObjectUtil.isNotEmptyList(storeIds) ){
            throw GlobalException.gen(10100, "门店id不存在");
        }

        LambdaQueryWrapper<DmsDevicePreloadEntity> lqs = new LambdaQueryWrapper();
        lqs.in(DmsDevicePreloadEntity::getStoreId, storeIds);
        devicePreloadMapper.selectList(lqs);
        lqs.eq(DmsDevicePreloadEntity::getStatus, 0);
        List<DmsDevicePreloadEntity> list = devicePreloadMapper.selectList(lqs);

        List<TmsStoreEntity> tmsStoreEntities = storeMapper.selectBatchIds(storeIds);
        if( ObjectUtil.isNotEmptyList(tmsStoreEntities) ){
            for( DmsDevicePreloadEntity item : list ){
                tmsStoreEntities.stream().filter(row-> row.getId().equals(item.getStoreId()))
                        .findFirst().ifPresent(row->{
                            item.setStoreName(row.getName());
                            item.setStoreNumber(row.getNumber());
                        });
            }
        }
        return list;
    }

    /**
     * 新增 DevicePreload
     * */
    @Transactional
    public void addDevicePreload(DmsDevicePreloadVo dmsDevicePreloadVo) throws Exception {

        Long timestamp = new Date().getTime();
        timestamp = timestamp + 3600 * 24 * 60;

        DmsDevicePreloadEntity dmsDevicePreloadEntity = new DmsDevicePreloadEntity();
        ReflectionCopy.copyProperties( dmsDevicePreloadEntity, dmsDevicePreloadVo );
        dmsDevicePreloadEntity.setExpires(new Date(timestamp));
        devicePreloadMapper.insert(dmsDevicePreloadEntity);
        return;
    }


    /**
     * 更新 DevicePreload
     * */
    @Transactional
    public void updateDevicePreload( DmsDevicePreloadVo dmsDevicePreloadVo) throws Exception {

        if( dmsDevicePreloadVo.getId() == null ){
            throw GlobalException.gen(10021, "id不存在");
        }

        DmsDevicePreloadEntity detail = devicePreloadMapper.selectById(dmsDevicePreloadVo.getId());
        if( detail == null ){
            throw GlobalException.gen(10021, "记录不存在");
        }

        DmsDevicePreloadEntity dmsDevicePreloadEntity = new DmsDevicePreloadEntity();
        ReflectionCopy.copyProperties( dmsDevicePreloadEntity, dmsDevicePreloadVo );
        devicePreloadMapper.updateById(dmsDevicePreloadEntity);

        String deviceIdString = detail.getDeviceIds();
        List<String> devices = JSON.parseArray(deviceIdString, String.class);
        for( String deviceNo : devices ){
            LambdaQueryWrapper<DmsDeviceInfoEntity> deviceLqs = new LambdaQueryWrapper();
            deviceLqs.eq(DmsDeviceInfoEntity::getNumber, deviceNo);
            DmsDeviceInfoEntity deviceInfo = new DmsDeviceInfoEntity();
            deviceInfo.setNumber(deviceNo);
            deviceInfo.setDeployDate(new Date());
            deviceInfo.setDeployCode(detail.getCode());
            deviceInfoMapper.update(deviceInfo,deviceLqs);
        }

        return;
    }

    /**
     * 删除 DevicePreload
     * */
    @Transactional
    public void batchRemoveDevicePreload( List<Long> ids ) throws Exception {

        if( !ObjectUtil.isNotEmptyList(ids) ){
            throw GlobalException.gen(10011, "要删除的id不存在");
        }
        devicePreloadMapper.deleteBatchIds(ids);
    }


}